// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.TransactionReceivableReportManagement;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.TransactionReceivableReportManagementItemMapper;
import com.fowo.api.mapper.TransactionReceivableReportManagementMapper;
import com.fowo.api.model.transaction.receivable.report.management.TransactionReceivableReportManagementExcelPo;
import com.fowo.api.model.transaction.receivable.report.management.TransactionReceivableReportManagementItemVo;
import com.fowo.api.model.transaction.receivable.report.management.TransactionReceivableReportManagementSearchParamPo;
import com.fowo.api.model.transaction.receivable.report.management.TransactionReceivableReportManagementVo;
import com.fowo.api.model.transaction.receivable.report.management.constant.TransactionReceivableReportManagementStateEnums;
import com.fowo.api.model.transaction.receivable.report.management.item.TransactionReceivableReportManagementItemSearchParamPo;
import com.fowo.api.service.TransactionReceivableReportManagementItemService;
import com.fowo.api.service.TransactionReceivableReportManagementService;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartFile;

/**
 * 应收交易报告管理 服务实现基类
 * @author 蜂窝蜜造平台 配置人：吕家傲，任凯
 */
@Slf4j
@DataObjectType(TransactionReceivableReportManagement.class)
@DS("ds24")
public class TransactionReceivableReportManagementBaseServiceImpl
  extends ServiceImpl<TransactionReceivableReportManagementMapper, TransactionReceivableReportManagement>
  implements TransactionReceivableReportManagementService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("stationName", "sr.`name`");
      put("sidShopName", "si.`shop_name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected TransactionReceivableReportManagementService self;

  @Resource
  protected TransactionReceivableReportManagementItemService transactionReceivableReportManagementItemService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Resource
  protected Validator validator;

  /**
   * 创建应收交易报告管理
   * @param model 应收交易报告管理
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(TransactionReceivableReportManagementVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TransactionReceivableReportManagement entity =
      new TransactionReceivableReportManagement();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getState() == null) {
      entity.setState("0");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("应收交易报告管理保存失败");
  }

  /**
   * 更新所有子表
   * @param model 应收交易报告管理
   */
  protected void updateAllChilds(TransactionReceivableReportManagementVo model)
    throws Exception {
    if (model.getItemList() != null) {
      transactionReceivableReportManagementItemService.saveAllByParentTransactionReceivableReportManagement(
        model.getId(),
        model.getItemList()
      );
    }
  }

  /**
   * 更新应收交易报告管理
   * @param model 应收交易报告管理
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(TransactionReceivableReportManagementVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TransactionReceivableReportManagement entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("应收交易报告管理不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新应收交易报告管理（带空值）
   * @param model 应收交易报告管理
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(TransactionReceivableReportManagementVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    TransactionReceivableReportManagement entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("应收交易报告管理不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        TransactionReceivableReportManagement::getStation,
        model.getStation()
      )
      .set(TransactionReceivableReportManagement::getSid, model.getSid())
      .set(
        TransactionReceivableReportManagement::getBillingTime,
        model.getBillingTime()
      )
      .set(
        TransactionReceivableReportManagement::getLastUpdateTime,
        model.getLastUpdateTime()
      )
      .set(
        TransactionReceivableReportManagement::getLastUpdateUser,
        model.getLastUpdateUser()
      )
      .set(
        TransactionReceivableReportManagement::getAccountType,
        model.getAccountType()
      )
      .set(
        TransactionReceivableReportManagement::getBillingTimeZone,
        model.getBillingTimeZone()
      )
      .set(TransactionReceivableReportManagement::getAmount, model.getAmount())
      .set(
        TransactionReceivableReportManagement::getCurrency,
        model.getCurrency()
      )
      .set(
        TransactionReceivableReportManagement::getUploadTime,
        model.getUploadTime()
      )
      .set(TransactionReceivableReportManagement::getState, model.getState())
      .set(
        TransactionReceivableReportManagement::getSummaryReport,
        model.getSummaryReport()
      )
      .set(
        TransactionReceivableReportManagement::getTransactionReport,
        model.getTransactionReport()
      )
      .set(
        TransactionReceivableReportManagement::getSummaryincome,
        model.getSummaryincome()
      )
      .set(
        TransactionReceivableReportManagement::getSummaryexpenses,
        model.getSummaryexpenses()
      )
      .set(
        TransactionReceivableReportManagement::getSummarytransfers,
        model.getSummarytransfers()
      )
      .set(
        TransactionReceivableReportManagement::getSummarytax,
        model.getSummarytax()
      )
      .set(
        TransactionReceivableReportManagement::getBillingTimestring,
        model.getBillingTimestring()
      )
      .eq(TransactionReceivableReportManagement::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    TransactionReceivableReportManagementSearchParamPo search
  ) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 子表(itemList) 对应的对象
    TransactionReceivableReportManagementItemSearchParamPo itemListSearchParam =
      new TransactionReceivableReportManagementItemSearchParamPo();
    itemListSearchParam.setDisableDataPremissions(true);
    itemListSearchParam.setParentTransactionReceivableReportManagementInList(
      ids
    );
    TransactionReceivableReportManagementItemMapper localTransactionReceivableReportManagementItemMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(TransactionReceivableReportManagementItemMapper.class);
    itemListSearchParam.applySqlSegments();
    List<Long> itemListIdList =
      localTransactionReceivableReportManagementItemMapper.searchIds(
        itemListSearchParam
      );
    if (!itemListIdList.isEmpty()) {
      TransactionReceivableReportManagementItemService localTransactionReceivableReportManagementItemService =
        ContextHolder
          .getApplicationContext()
          .getBean(TransactionReceivableReportManagementItemService.class);
      localTransactionReceivableReportManagementItemService.batchDelete(
        itemListIdList
      );
    }
  }

  /**
   * 删除应收交易报告管理
   * @param id 应收交易报告管理的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除应收交易报告管理
   * @param ids 应收交易报告管理的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    TransactionReceivableReportManagementSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "station",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((TransactionReceivableReportManagementItemVo) r).getStationName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "accountType",
        new CustomExcelExport.FieldMappingOption().setDictCode(" SCM00233")
      );
      exportOptions.addFieldMappingOption(
        "state",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            TransactionReceivableReportManagementStateEnums.toLabel((String) o)
          )
      );
      exportOptions.addStringFields(
        "stationName",
        "accountType",
        "billingTimeZone",
        "currency",
        "state",
        "billingTimestring"
      );

      String fileName = String.format(
        "应收交易报告管理(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> accountTypeItems = sysDictService.getDictItems(
      " SCM00233"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<TransactionReceivableReportManagementExcelPo> items =
      new ArrayList<TransactionReceivableReportManagementExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<TransactionReceivableReportManagementItemVo> page =
        this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<TransactionReceivableReportManagementItemVo> list =
        page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (TransactionReceivableReportManagementItemVo item : list) {
        TransactionReceivableReportManagementExcelPo excel =
          new TransactionReceivableReportManagementExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getAccountType() != null) {
          accountTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getAccountType()))
            .findFirst()
            .ifPresent(i -> excel.setAccountType(i.getItemText()));
        }
        excel.setState(
          TransactionReceivableReportManagementStateEnums.toLabel(
            item.getState()
          )
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "应收交易报告管理(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(TransactionReceivableReportManagementExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过账单日期文本查询应收交易报告管理主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByBillingTimestring(String billingTimestring) {
    return this.baseMapper.getIdByBillingTimestring(billingTimestring);
  }

  /**
   * 通过账单日期文本查询应收交易报告管理多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByBillingTimestring(List<String> list) {
    return this.baseMapper.getIdsByBillingTimestring(list);
  }

  /**
   * 通过应收交易报告管理主键查询账单日期文本
   */
  @Override
  public String getBillingTimestringById(Long id) {
    return this.baseMapper.getBillingTimestringById(id);
  }

  /**
   * 通过应收交易报告管理主键查询账单日期文本列表
   */
  @Override
  public List<String> getBillingTimestringByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getBillingTimestringByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("billingTimestring")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 应收交易报告管理的主键
   */
  @Override
  public TransactionReceivableReportManagementVo getVoById(Long id)
    throws Exception {
    TransactionReceivableReportManagementVo vo =
      this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    TransactionReceivableReportManagementItemSearchParamPo itemListSearchParamPo =
      new TransactionReceivableReportManagementItemSearchParamPo();
    itemListSearchParamPo.setParentTransactionReceivableReportManagement(id);
    // 禁用通用数据权限过滤
    itemListSearchParamPo.setDisableDataPremissions(true);
    itemListSearchParamPo.applySqlSegments();
    vo.setItemList(
      transactionReceivableReportManagementItemService.search(
        itemListSearchParamPo
      )
    );

    return vo;
  }

  /**
   * 分页查询应收交易报告管理
   * @param search 查询条件
   * @return 应收交易报告管理分页查询结果
   */
  @Override
  public Page<TransactionReceivableReportManagementItemVo> pageSearch(
    TransactionReceivableReportManagementSearchParamPo search
  ) {
    Page<TransactionReceivableReportManagementItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(TransactionReceivableReportManagementItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 应收交易报告管理快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'TransactionReceivableReportManagementOptions::' + #search.keyword"
  )
  public List<OptionItem<TransactionReceivableReportManagementItemVo>> searchOptions(
    TransactionReceivableReportManagementSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询应收交易报告管理
   * @param search 查询条件
   * @return 应收交易报告管理列表查询结果
   */
  @Override
  public List<TransactionReceivableReportManagementItemVo> search(
    TransactionReceivableReportManagementSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询应收交易报告管理最后更新时间
   * @param search 查询条件
   * @return 应收交易报告管理最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(
    TransactionReceivableReportManagementSearchParamPo search
  ) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 导入交易报告
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importReport(Long id, MultipartFile file) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/TransactionReceivableReportManagement_importReport.js",
      id,
      new ExecuteScriptEngine.OtherArgs().applyUploadData(file),
      this
    );
  }

  /**
   * 上传记录
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void uploadRecord(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/TransactionReceivableReportManagement_uploadRecord.js",
      id,
      null,
      this
    );
  }

  /**
   * 批量
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void batchs(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/TransactionReceivableReportManagement_batchs.js",
      id,
      null,
      this
    );
  }
}
